local Msg = require("core.Msg")
local Human = require("core.Human")
local MakeTencentCommonParam = require("tencentApi.Define").MakeTencentCommonParam
local Define = require("tencentApi.Define")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local PfLogic = require("tencentApi.PfLogic")
Json = Json or require("common.Json")
local BlueOtherReward = require("excel.Yellow").blueOther[1]
local Grid = require("bag.Grid")
local Log = require("common.Log")
local MailLogicFW = require("mail.MailLogicFW")
local InnerDataDefine = require("innerdata.Define")
local InnerDataManager = require("innerdata.InnerDataManagerFW")

local s2aParam = {}
BLUR_GET_TOKEN_DATA = BLUR_GET_TOKEN_DATA or {}

function blueVipInfo(human, login) --蓝钻信息查询
    local pf_info = human.pf_info
    if pf_info == nil then
        return
    end
    if not PfLogic.isBlueShow(human) then
        return
    end
    if login and pf_info.blueHadLogin then
        return
    end
    if login then
        pf_info.blueHadLogin = true
    end
   -- 构造参数
    local callback_general_param = {}
    callback_general_param.account = human.account
    callback_general_param.name = human.name
    callback_general_param.login = login
    s2aParam.callback_general_param = callback_general_param
    local api_param = MakeTencentCommonParam(pf_info)
    s2aParam.api_param = api_param    
    s2aParam.api_url = "/v3/user/blue_vip_info"
    s2aParam.api_cbMethod = "OnBlueVipInfoReturn"
    _G.thread_http.send(Define.DELIVER_PHP,Json.Encode(s2aParam))
end

blueExpireRewardGridCache = nil
local function getContinueBlueReward()
    if blueExpireRewardGridCache  ~= nil then
        return blueExpireRewardGridCache
    end
    blueExpireRewardGridCache = {}
    for i = 1, #BlueOtherReward.continueReward do
        local grid = {}
        Grid.create(grid, BlueOtherReward.continueReward[i][1], BlueOtherReward.continueReward[i][2], BlueOtherReward.continueReward[i][3])
        blueExpireRewardGridCache[i] = grid
        if i == 3 then
           break
        end 
    end
    return 
end

local EXPIRE_TIME = 3*24*3600 

function OnBlueVipInfoReturn(resultJson)
    local respond = {}
    respond.ret = 0
    respond.msg = "fail"
    
    local tencent_ret = resultJson.tencent_ret
    local general_param = resultJson.callback_general_param
    
    local name = general_param.name
    if name == nil then
        print("OnBlueVipInfoReturn: Callback param's name should not be null")
        return Json.Encode(respond)
    end
    local human = Human.onlineHuman[name]
    if human == nil or not human.fd then
        print("OnBlueVipInfoReturn:Human offlined")
        return  Json.Encode(respond)
    end
    if not PfLogic.isBlueShow(human) then
        print("not show blue....")
        return Json.Encode(respond)
    end
    if tencent_ret.ret ~= 0 then
        print("Transaction failed, ret:", tencent_ret.ret, " msg:", tencent_ret.msg)
        if tencent_ret.ret == 1002 then
          Broadcast.sendBroadcast(human,Lang.MOUSE,"登录状态超时，请刷新游戏后再次尝试")
        end
        return Json.Encode(respond)
    end
    
    respond.ret = 1
    respond.msg = "success"
    local now = os.time()
    tencent_ret.is_super_blue_vip = tencent_ret.is_super_blue_vip or 0

    human.db.blueVip = tencent_ret.is_blue_vip 
    human.db.blueVipLv = tencent_ret.blue_vip_level 
    human.db.blueYearVip = tencent_ret.is_blue_year_vip
    human.db.blueSuperVip = tencent_ret.is_super_blue_vip
    human.db.blueVipValidTime = tencent_ret.vip_valid_time - tencent_ret.server_time + now
    human.db.blueYearValidTime = tencent_ret.year_vip_valid_time - tencent_ret.server_time + now        
    human.db.blueSuperValidTime = tencent_ret.super_vip_valid_time - tencent_ret.server_time + now
       
    local mm = Msg.gc.GC_QQ_BLUE_EXPIRE
    mm.blue = 0
    mm.blueYear = 0 
    mm.blueSuper = 0
    if human.db.blueSuperValidTime ~= 0  and math.abs(now - human.db.blueSuperValidTime) <= EXPIRE_TIME  then
        mm.blueSuper = 1
        mm.expire = now > human.db.blueSuperValidTime and 2 or 1
    elseif now - human.db.blueYearValidTime ~= 0 and math.abs(now - human.db.blueYearValidTime) <= EXPIRE_TIME then
        mm.blueYear = 1
        mm.expire = now > human.db.blueYearValidTime and 2 or 1
    elseif human.db.blueVipValidTime ~= 0 and math.abs(now - human.db.blueVipValidTime) <= EXPIRE_TIME then
        mm.blue = 1
        mm.expire = now > human.db.blueVipValidTime and 2 or 1
    else
        mm.expire = 0
    end
    print("blue :", mm.expire)
    if mm.expire ~= 0 then
        getContinueBlueReward()
        for i = 1, #blueExpireRewardGridCache do
            Grid.makeItem(blueExpireRewardGridCache[i], mm.reward[i])
        end
        mm.reward[0] = #blueExpireRewardGridCache
    else
        mm.reward[0] = 0
    end
    Msg.send(mm, human.fd)   
    Human.sendBlueInfo(human)     
    if general_param.login then --刷新客户端蓝钻信息,加buf      
        InnerDataManager.Send2LInnerData(human, InnerDataDefine.INNERDATA_TYPE_BLUE_ADD)  
    end   
    return  Json.Encode(respond)  
end


function blueGetToken(human, type)
	local pf_info = human.pf_info
    if pf_info == nil  then
        return
    end
    if not PfLogic.isBlueShow(human) then
        return
    end
   -- 构造参数
    local callback_general_param = {}
    callback_general_param.account = human.account
    callback_general_param.name = human.name
    callback_general_param.blue_type = type
    s2aParam.callback_general_param = callback_general_param
    local api_param = MakeTencentCommonParam(pf_info)
    api_param.tokentype = 1
    api_param.discountid = Define.BLUE_MP_ID
    api_param.ts = os.time()
    api_param.version = "v3" 
    api_param.zoneid = pf_info.zoneid
    s2aParam.api_param = api_param
    
	  s2aParam.api_url = "/v3/pay/get_token"
    s2aParam.api_cbMethod = "OnTokenReturnForOpenVip"
	  _G.thread_http.send(Define.DELIVER_PHP,Json.Encode(s2aParam))
	  
	  local posOpenID = string.find(human.account, "-")
    local openID = human.account
    if posOpenID then
      openID = string.sub(human.account, posOpenID+1, -1)
    end
	  BLUR_GET_TOKEN_DATA[openID] = human._id	
end

function OnTokenReturnForOpenVip(result_json)
	local respond = {}
	respond.ret = 0
    respond.msg = "fail"
    local tencent_ret = result_json.tencent_ret
    local general_param = result_json.callback_general_param

    local human_name = general_param.name
    if (human_name == nil) then
        print("Callback param's name should not be null")
        return Json.Encode(respond)
    end

    local human = Human.onlineHuman[human_name]
    if human == nil or not human.fd then
        print("Human offlined")
        return  Json.Encode(respond)
    end

    if (tencent_ret.ret ~= 0) then
       --OPENKEY过期。 
        if tencent_ret.ret == 1002 then
			   Broadcast.sendBroadcast(human,Lang.MOUSE,"登录状态超时，请刷新游戏后再次尝试")
        end
        return Json.Encode(respond)
    end

    local token = tencent_ret.token
		local msg_ret = Msg.gc.GC_BLUE_KT_TOKEN
		msg_ret.token = token
		msg_ret.discountid = Define.BLUE_MP_ID
		msg_ret.type = general_param.blue_type
		Msg.send(msg_ret, human.fd)
    respond.ret = 1
    respond.msg = "success"
    return  Json.Encode(respond)
end

--开通黄钻发货回调
function OnYellowDeliverReturn(result_json)
  local respond = {}
  respond.ret = 0
  respond.msg = "OK"
  local discountid = result_json.discountid
  local openid = result_json.openid
  if discountid and discountid == Define.BLUE_MP_ID then
    if openid == nil then
      respond.msg = "openid is nil"
      return  Json.Encode(respond)
    end 
    local uuid = BLUR_GET_TOKEN_DATA[openid]
    if uuid == nil or uuid == "" then
      respond.msg = "uuid is nil"
      return  Json.Encode(respond)
    end  
    getContinueBlueReward()
    MailLogicFW.addSystemMessage(uuid, Lang.BLUE_CONTINUE_MAIL_TITLE,Lang.BLUE_CONTINUE_MAIL_CONTENT, blueExpireRewardGridCache)    
    local human = Human.onlineUuid[uuid]
    if human then
        blueVipInfo(human)
    end
    BLUR_GET_TOKEN_DATA[openid] = nil
    Log.write(Log.LOGID_OSS_OPENVIP_BLUE, uuid, openid, discountid)
  end
  return  Json.Encode(respond)
end